/**
 * @file dev_mpu.c
 * @brief
 * @author He Shaohua (hsh15529870639@foxmail.com)
 * @date 2024-07-29
 * @version 1.0
 * @copyright Copyright (c) 2024, SNUT-Chaoyue Team
 * ****************************************************************************************************
 * @par Change Log:
 * <table>
 * <tr><th>Date         <th>Version       <th>Author      <th>Description
 * <tr><td>2024-07-29   <td> 1.0          <td>He Shaohua  <td>Creator
 *
 * </table>
 * ==================================----How to use this driver----=====================================
 * [..]
 * @note
 *   -#
 *
 * @warning
 *   -#
 *
 * *****************************************************************************************************
 * @attention
 *
 * This document is required and please understand any bugs that may occur in the document.
 * If you want to modify this file, after the code update is completed, update the version number in time,
 * indicate the update date, and fill in the changes
 * Make sure that the submitted code does not have many bugs.
 *
 * All rights reserved.
 * *****************************************************************************************************
 */
#include "dev_mpu.h"

float imu_yaw = 0.0f;

static uint8_t check_sum(uint8_t *Address, uint32_t Length)
{
  uint8_t sum = 0;
  for (int i = 0; i < Length; i++)
  {
    sum += Address[i];
  }
  return (sum);
};

typedef enum
{
  Stata_0 = 0,
  Stata_1,
  Stata_2,
  Stata_3,
  Stata_4,
  Stata_5,
} stata;

static stata stata_list = Stata_0;
static uint8_t data_num = 0;
uint8_t RX_Buffer[11] = {0};
void IMU_INST_IRQHandler(void)
{
  switch (DL_UART_Main_getPendingInterrupt(IMU_INST))
  {
    uint8_t gEchoData;
  case DL_UART_MAIN_IIDX_RX:
    gEchoData = DL_UART_Main_receiveData(IMU_INST);
    switch (stata_list)
    {
    case Stata_0:
      if (gEchoData == 0x55)
      {
        RX_Buffer[0] = 0x55;
        stata_list = Stata_1;
      }
      break;

    case Stata_1:

      if (gEchoData == 0x53)
      {
        RX_Buffer[1] = 0x53;
        data_num = 0;
        stata_list = Stata_2;
      }
      else
      {
        stata_list = Stata_0;
      }
      break;

    case Stata_2:
      data_num++;
      RX_Buffer[data_num + 1] = gEchoData;
      if (data_num == 8)
      {
        stata_list = Stata_3;
      }
      break;

    case Stata_3:
      if (gEchoData == check_sum(RX_Buffer, 10))
      {
        imu_yaw = (float)((int16_t)(RX_Buffer[6] | RX_Buffer[7] << 8) / 32768.0f * 180.0f);
        stata_list = Stata_0;
      }
      break;

    default:
      break;
    }
    break;
  default:
    break;
  }
}
